package com.example.demo3.listener;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import org.flowable.common.engine.api.delegate.Expression;
import org.flowable.engine.RuntimeService;
import org.flowable.engine.delegate.DelegateExecution;
import org.flowable.engine.delegate.ExecutionListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

@Component(value = "labelListener")
public class LabelExecutionListener implements ExecutionListener {
    @Autowired
    RuntimeService runtimeService;
    Expression label;

    @Override
    public void notify(DelegateExecution execution) {
        System.out.println("执行监听器：" + execution.getEventName());

        List<Integer> labelList = Convert.convert(List.class, execution.getVariable("labelList"));
        if (ObjectUtil.isNotEmpty(labelList)) {
            if (ObjectUtil.equals("0", label.getExpressionText())) {
                if (!labelList.contains(0)) {
                    runtimeService.deleteProcessInstance(execution.getProcessInstanceId(), "结束流程");
                }
            } else if (ObjectUtil.equals("1", label.getExpressionText())) {
                if (labelList.contains(1)) {
                    runtimeService.deleteProcessInstance(execution.getProcessInstanceId(), "结束流程");
                }
            } else if (ObjectUtil.equals("2", label.getExpressionText())) {
                long count0 = labelList.stream().filter(l -> l == 0).count();
                long count1 = labelList.stream().filter(l -> l == 1).count();
                if (count1 >= count0) {
                    runtimeService.deleteProcessInstance(execution.getProcessInstanceId(), "结束流程");
                }
            }
        }
    }
}
